<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-19 00:34:34
 * Desc:
 */

namespace app\api\controller;

use app\api\service\WishRecommendService;
use app\api\service\UserRegisterService;
use app\api\service\GoodsService;
use app\base\model\user\UserAccountLog;
use app\base\model\order\Order;
use app\base\model\system\SystemConfig;
use app\core\exception\BusinessException;
use app\core\util\PreVentRepeatSubmitUtil;
use app\core\cache\RedisKeys;
use app\core\exception\ErrorCode;
use app\core\log\Log4dd;
use think\Request;

class HomeController extends ApiBaseController
{
    protected $beforeActionList = [
        'checkLogin',
        'getSysCurrencyName',
        'checkAccountState',
        'getAccountType'
    ];

    public function getHomeMenuList()
    {
        //  如果用户打开小程序进入首页时圈子筛选栏中有心愿信息，则默认选中圈子
        //  如果用户打开小程序进入首页时圈子筛选栏中没有任何心愿信息，则默认选中广场-推荐
        $circle_have_data = WishRecommendService::circleHaveData($this->user_id);
        $data = [
            [
                'menu_name' => WishRecommendService::MENU_KEY_CIRCLE_NAME,
                'menu_key' => WishRecommendService::MENU_KEY_CIRCLE,
                'menu_color' => '#000000',
                'is_default' => $circle_have_data ? 1 : 0,
                'red_dot' => 0,
                'page_size' => 15,
                'sub_menu' => []
            ],
            [
                'menu_name' => WishRecommendService::MENU_KEY_SQUARE_NAME,
                'menu_key' => WishRecommendService::MENU_KEY_SQUARE,
                'menu_color' => '#000000',
                'is_default' => $circle_have_data ? 0 : 1,
                'red_dot' => 1,
                'page_size' => 15,
                'sub_menu' => [
                    /*[
                        'menu_name' => WishRecommendService::MENU_KEY_SQUARE_RECOMMEND_NAME,
                        'menu_key' => WishRecommendService::MENU_KEY_SQUARE_RECOMMEND,
                        'menu_color' => '#FFFFFF',
                        'is_default' => $circle_have_data ? 0 : 1,
                        'red_dot' => 0,
                        'page_size' => 15,
                    ],
                    [
                        'menu_name' => WishRecommendService::MENU_KEY_SQUARE_NEW_NAME,
                        'menu_key' => WishRecommendService::MENU_KEY_SQUARE_NEW,
                        'menu_color' => '#000000',
                        'is_default' => 0,
                        'red_dot' => 0,
                        'page_size' => 15,
                    ],*/
                ]
            ],
        ];

        return $this->successReturn($data);

    }

    public function getHomeList()
    {
        try {
            $menu_key = input('menu_key/s', '');

            $page_size = input('page_size/d', 15);

            $page = input('page/d', 1);

            $param_first_timestamp = input('first_timestamp/d', 1);
            $result = [];
            $recommend = [];
            switch ($menu_key) {
                case WishRecommendService::MENU_KEY_CIRCLE://圈子
                    $data = WishRecommendService::getCircleList($this->user_id);
                    break;
                case WishRecommendService::MENU_KEY_SQUARE://广场
                    $where = [];
                    if ($page == 1) {
                        $recommend = WishRecommendService::getSquareRecommendList($this->user_id);
                        if ($recommend) {
                            $where['g.group_id'] = ['not in', array_column($recommend, 'group_id')];
                        }
                    }
                    $data = WishRecommendService::getSquareNewList($this->user_id, $where);
                    //$data = WishRecommendService::getSquareRecommendList($this->user_id);
                    break;
                case WishRecommendService::MENU_KEY_SQUARE_RECOMMEND://广场->推荐 包含自己帮付过款的
                    $data = WishRecommendService::getSquareRecommendList($this->user_id);
                    break;
                case WishRecommendService::MENU_KEY_SQUARE_NEW://广场->最新
                    $data = WishRecommendService::getSquareNewList($this->user_id);
                    break;
                default:
                    $data = WishRecommendService::getCircleList($this->user_id);
                    break;
            }

            $list = array_slice($data, ($page - 1) * $page_size, $page_size);

            $first_timestamp =  $list ? $list[0]['timestamp'] : 0;

            if ($menu_key == WishRecommendService::MENU_KEY_SQUARE) {
                $result = [
                    [
                        'label' => WishRecommendService::MENU_KEY_SQUARE_RECOMMEND_NAME,
                        'list' => $recommend,
                    ],
                    [
                        'label' => WishRecommendService::MENU_KEY_SQUARE_NEW_NAME,
                        'list' => $list,
                        'count' => count($data),
                        'page' => $page,
                        'page_size' => $page_size,
                        'first_timestamp' => $page == 1 ? $first_timestamp : 0,
                        'red_dot' => $page == 1 && $first_timestamp > $param_first_timestamp ? 1 : 0
                    ]
                ];
            } elseif ($menu_key == WishRecommendService::MENU_KEY_CIRCLE) {
                $result = [
                    [
                        'label' => '',//WishRecommendService::MENU_KEY_CIRCLE_NAME,
                        'list' => $list,
                        'count' => count($data),
                        'page' => $page,
                        'page_size' => $page_size,
                        'first_timestamp' => $page == 1 ? $first_timestamp : 0,
                        'red_dot' => $page == 1 && $first_timestamp > $param_first_timestamp ? 1 : 0
                    ]
                ];
            }

            return $this->successReturn($result);
        } catch (BusinessException $e) {
            Log4dd::error('获取首页数据失败', ['user_id' => $this->user_id, 'param' => Request::instance()->param(false)], $e);
            return $this->errorReturn($e->getCode(), $e->getMessage());
        }

    }

    /**
     * Desc: 获取首页弹窗
     * Date: 2020/2/10 22:32
     * Author: yiyu
     * @return \think\response\Json
     */
    public function getHomePopUpsData()
    {
        $data = [];
        $give_info = UserAccountLog::hasAlreadyReceivedRegisterReward($this->user_id);

        if (empty($give_info)) {
            //判断用户是否付费
            $has_pay = Order::hasPay($this->user_id);
            if (!$has_pay) {
                $register_give_wish_coin_num = SystemConfig::getNewUserGiveWishCoinNum();
                $first_support_extra_give = GoodsService::getFirstSupportWishGiveWishCoinNum();

                $welfare1 = [
                    'tips' => '福利一',
                    'title' => $register_give_wish_coin_num . $this->currency_name,
                    'content' => '可用于发起价值￥' . $register_give_wish_coin_num . '的好物心愿'
                ];

                $welfare2 = [
                    'tips' => '福利二',
                    'title' => '首次支持特权',
                    'content' => '首次支持他人，你多得' . $first_support_extra_give . $this->currency_name
                ];

                $register_give = [
                    'name' => 'register_give',
                    'background_color' => '',
                    'background_img' => '',
                    'data' => [
                        'top_title' => '',
                        'element' => [

                        ],
                        'button_info' => [
                            'button_name' => '立即领取',
                            'button_color' => '',
                        ]
                    ],
                ];

                if ($first_support_extra_give) {
                    $register_give['data']['top_title'] = '新人二重礼';
                    $register_give['data']['element'][] = $welfare1;
                    $register_give['data']['element'][] = $welfare2;
                } else {
                    $register_give['data']['top_title'] = '新人红包';
                    $welfare1['tips'] = '';
                    $register_give['data']['element'][] = $welfare1;
                }

                $data[] = $register_give;
            }
        }

        Log4dd::info('获取首页弹窗', ['user_id' => $this->user_id, 'give_info' => $give_info, 'data' => $data]);
        return $this->successReturn($data);
    }

    /**
     * Desc: 确认赠送注册奖励 需全部返回成功
     * Date: 2020/2/10 21:33
     * Author: yiyu
     * @return \think\response\Json
     */
    public function giveRegisterReward()
    {
        try {
            //防重复提交
            PreVentRepeatSubmitUtil::check(RedisKeys::getRegisterGiveKey($this->user_id));
            $register_give_wish_coin_num = UserRegisterService::RegisterGiveWishCoin($this->user_id);

            if (!$register_give_wish_coin_num) {
                return $this->successReturn(['state' => 'error'], '领取失败');
            }

            return $this->successReturn([
                'state' => 'success',
                'register_give_wish_coin_num' => SystemConfig::getNewUserGiveWishCoinNum(),//赠送的心愿值
                'wish_coin_effect' => SystemConfig::getWishCoinEffect(),//心愿值用处描述
                'goods_list' => GoodsService::getRecommendGoodsInfos($this->user_id, $register_give_wish_coin_num)//推荐的商品列表
            ]);
        } catch (BusinessException $e) {
            return $this->successReturn(['state' => 'error'], $e->getMessage());
        }
    }

}